package online.yysh.charging.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatDialog;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import online.yysh.charging.AboutUsActivity;
import online.yysh.charging.BalanceActivity;
import online.yysh.charging.BindPhoneActivity;
import online.yysh.charging.FeedbackActivity;
import online.yysh.charging.MyPreChargeActivity;
import online.yysh.charging.OrderActivity;
import online.yysh.charging.R;
import online.yysh.charging.WithdrawalActivity;
import online.yysh.charging.base.BaseFragment;
import online.yysh.charging.bean.Login;
import online.yysh.charging.livedata.BindPhoneManager;
import online.yysh.charging.livedata.UserManager;
import online.yysh.charging.utils.Constant;
import online.yysh.charging.wxapi.WXConstant;
import online.yysh.charging.livedata.WXLoginManager;
import online.yysh.charging.wxapi.WXLogin;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * 我的页面
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private TextView tv_phoneNumber, tv_status;
    private ImageView iv_head;
    private LinearLayout ll_orders, ll_recharge, ll_withdrawal, ll_bind,ll_account,ll_feedback,ll_about_us,ll_booking;
    private LinearLayout ll_customerService;

    private SharedPreferences sp;

    public MineFragment() {

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        tv_phoneNumber = view.findViewById(R.id.tv_phoneNumber);
        tv_status = view.findViewById(R.id.tv_status);
        iv_head = view.findViewById(R.id.iv_head);
        ll_orders = view.findViewById(R.id.ll_orders);
        ll_orders.setOnClickListener(this);
        ll_recharge = view.findViewById(R.id.ll_recharge);
        ll_recharge.setOnClickListener(this);
        ll_withdrawal = view.findViewById(R.id.ll_withdrawal);
        ll_withdrawal.setOnClickListener(this);
        ll_customerService = view.findViewById(R.id.ll_customerService);
        ll_customerService.setOnClickListener(this);
        ll_bind = view.findViewById(R.id.ll_bind);
        ll_bind.setOnClickListener(this);
        ll_account = view.findViewById(R.id.ll_account);
        ll_account.setOnClickListener(this);
        ll_feedback = view.findViewById(R.id.ll_feedback);
        ll_feedback.setOnClickListener(this);
        ll_about_us = view.findViewById(R.id.ll_about_us);
        ll_about_us.setOnClickListener(this);
        ll_booking = view.findViewById(R.id.ll_booking);
        ll_booking.setOnClickListener(this);
        return view;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        sp = getActivity().getSharedPreferences(Constant.SP_NAME, Context.MODE_PRIVATE);
        tv_phoneNumber.setText(sp.getString(Constant.SP_KEY_BIND_PHONE, getResources().getString(R.string.unbind_phone_number)));
        String headImgUrl = sp.getString(Constant.SP_KEY_HEAD_IMAGE_URL,"");
        if (TextUtils.isEmpty(headImgUrl)){
            //未登录时显示的头像
            Glide.with(getActivity())
                    .load(getResources().getDrawable(R.drawable.login_wechat_ic))
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(iv_head);
        }else{
            showHeadImage(headImgUrl);
            tv_status.setText(sp.getString(Constant.SP_KEY_NICK_NAME,""));
        }

        //监听微信登陆
        WXLoginManager.getInstance().getLiveData().observe(this, new Observer<WXLogin>() {
            @Override
            public void onChanged(WXLogin wxLogin) {
                String headImgUrl = wxLogin.getHeadImgUrl();
                String nickName = wxLogin.getNickName();
                showHeadImage(headImgUrl);
                tv_status.setText(nickName);
            }
        });
        //监听手机号绑定
        BindPhoneManager.getInstance().getLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                tv_phoneNumber.setText(s);
                sp.edit().putString(Constant.SP_KEY_BIND_PHONE, s).commit();
            }
        });
    }

    /**
     * 恢复用户信息至初始状态
     */
    private void restoreUser(){
        Glide.with(getActivity())
                .load(getResources().getDrawable(R.drawable.login_wechat_ic))
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(iv_head);
        tv_status.setText(R.string.wx_login);
        tv_phoneNumber.setText(R.string.unbind_phone_number);
        sp.edit().putString(Constant.SP_KEY_BIND_PHONE,getResources().getString(R.string.unbind_phone_number))
                .putString(Constant.SP_KEY_NICK_NAME,"")
                .putString(Constant.SP_KEY_HEAD_IMAGE_URL,"")
                .putString(Constant.SP_KEY_OPENID,"")
                .commit();
        UserManager.getInstance().getLiveData().setValue(new Login().setOpenid(""));
    }

    private void showHeadImage(String headImgUrl){
        Glide.with(getActivity())
                .load(headImgUrl)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(iv_head);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_account:
                //未登录时跳转至微信登录，已登录的弹出是否退出微信登录
                if (TextUtils.isEmpty(sp.getString(Constant.SP_KEY_OPENID,""))){
                    wxLogin();

                }else {
                    showLogoutDialog();
                }
                break;
            case R.id.ll_orders:
                startActivity(new Intent(getActivity(), OrderActivity.class));
                break;
            case R.id.ll_recharge:
                startActivity(new Intent(getActivity(),BalanceActivity.class));
                break;
            case R.id.ll_withdrawal:
                startActivity(new Intent(getActivity(), WithdrawalActivity.class));
                break;
            case R.id.ll_customerService:
                showCallDialog();
                break;
            case R.id.ll_bind:
                String number = tv_phoneNumber.getText().toString().trim();
                if (!TextUtils.isEmpty(number) && number.length() == 11){
                    return;
                }
                startActivity(new Intent(getActivity(), BindPhoneActivity.class));
                break;
            case R.id.ll_feedback:
                startActivity(new Intent(getActivity(), FeedbackActivity.class));
                break;
            case R.id.ll_about_us:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            case R.id.ll_booking:
                Intent intent = new Intent(getActivity(), MyPreChargeActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 弹出登录对话框
     */
    private void showLogoutDialog() {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(getActivity());
        View view = getLayoutInflater().inflate(R.layout.dialog_logout, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出登录逻辑
                restoreUser();
                appCompatDialog.dismiss();
            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 弹出拨打电话对话框
     */
    private void showCallDialog() {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(getActivity());
        View view = getLayoutInflater().inflate(R.layout.dialog_call, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                call();
                appCompatDialog.dismiss();

            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(800, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }

    /**
     * 微信登陆
     */
    private void wxLogin() {
        IWXAPI WXapi = WXAPIFactory.createWXAPI(getActivity(), WXConstant.WX_APP_ID, true);
        WXapi.registerApp(WXConstant.WX_APP_ID);
        //检测是否安装微信
        if (WXapi.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo";
            WXapi.sendReq(req);
        } else {
            showToast(getResources().getString(R.string.uninstall_wx));
        }
    }

    /**
     * 拨打客服电话
     */
    public void call() {
        String phoneNumber = getResources().getString(R.string.customer_phone_number);
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNumber);
        intent.setData(data);
        startActivity(intent);
    }

    /**
     * 充值对话框
     */
//    public void showRechargeDialog() {
//        final AppCompatDialog appCompatDialog = new AppCompatDialog(getActivity());
//        View view = getLayoutInflater().inflate(R.layout.dialog_recharge), null);
//        final EditText et_money = view.findViewById(R.id.et_money);
//        et_money.setFilters(new InputFilter[]{new CashierInputFilter()});
//        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
//        tv_cancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                appCompatDialog.dismiss();
//            }
//        });
//        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
//        tv_confirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String money = et_money.getText().toString().trim();
//                if (!TextUtils.isEmpty(money)) {
//                    String m = Float.valueOf(money) * 100+"";
//                    wxPay(Integer.parseInt(m.substring(0,m.indexOf("."))));
//                } else {
//                    Toast.makeText(getActivity(), "充值金额不能为空", Toast.LENGTH_SHORT).show();
//                }
//                appCompatDialog.dismiss();
//
//            }
//        });
//        appCompatDialog.setContentView(view);
//        Window window = appCompatDialog.getWindow();
//        window.setBackgroundDrawableResource(R.color.transparent);
//        window.setGravity(Gravity.CENTER);
//        window.setLayout(700, ViewGroup.LayoutParams.WRAP_CONTENT);
//        appCompatDialog.show();
//    }

}